package zw.netty.server.Netty.Handler;


import cn.hutool.core.text.StrFormatter;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson.TypeReference;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;
import zw.netty.server.pojo.Device;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 创建人:zhuwei
 * 邮箱:121203654@qq.com
 * 创建时间:2018-04-26 16:48
 */
public class HandUtil {

    public static String GetDateString(Date date,String format){
        SimpleDateFormat sf=new SimpleDateFormat(format);
        return sf.format(date);
    }

    public static String[] GetStringArray(String s){
        if(s!=null){
            return s.split(",");
        }
        return null;
    }

    public static String joinParam(Object... argArray){
        return StrFormatter.format("@G#@,V01,{},@R#@",argArray);
    }

    public static Device CreateDevice(String str){
        str=str.replace(",@R#@","");
        String[] strings= str.split(",");
        Device device=new Device();
        device.setSerial(strings[3]);
        device.setCurrentCmd(str);
        if(strings[2].equals("6")){
            device.setLocation(strings[6].replace(";",","));
            device.setCurrentCmd(device.getLocation());
        }else if(strings[2].equals("43")){
            HashMap<String, Object> paramMap = new HashMap<>();
            //String[] sst=strings[9].split("|");
            String[] ssss=strings[9].replace("|","#").split("#");
            //System.out.println(StringUtils.join(sst, ";"));
            for (int i = 0; i < ssss.length; i++) {
                String[] s = ssss[i].split(";");
                System.out.println(ssss[i]);
                if(s.length>=2){
                    ssss[i]=s[0]+","+s[2];
                }
            }
            paramMap.put("cl",strings[7].replace(";",",").replace("|",";"));
            paramMap.put("wl",StringUtils.join(ssss, ";"));
            paramMap.put("coord","gcj02");
            paramMap.put("output","json");
            JSONObject jsonObject=JSONObject.parseObject(HttpUtil.get("http://api.cellocation.com:81/loc/",paramMap));
            device.setLocation(jsonObject.getString("lat")+","+jsonObject.getString("lon"));
            device.setCurrentCmd(device.getLocation());
        }
        return device;
    }
    //78 78 06 17 18 08 04 09 42 44 a8154dfa177a5a 40f420c1572250 94d9b32d51b53e 487d2edddfe058 00271d04b44757  fc7c0260cfb758 02 01cc00 271729e85a 2717cb9664 0d 0a
    public static  String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }

        for (int i = 0; i < src.length; i++) {
            int v =(short)src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
            stringBuilder.append(" ");


        }
        return stringBuilder.toString();
    }

    /**
     * 处理汽车ODB数据
     * @param bytes
     * @return
     */
    public static String DateDecode(byte[] bytes){
        Queue<Byte> queueBuffer = new LinkedList<Byte>();
        byte[] packBuffer = new byte[11];
        for (int i = 0; i < bytes.length; i++) {
            byte aByte = bytes[i];
            queueBuffer.add(aByte);
        }
        int sHead;
        JSONObject json=new JSONObject();
        while(queueBuffer.size()>0){
            sHead=queueBuffer.poll()& 0xFF;
            for (int i = 0; i < 5; i++) {
                try {
                    packBuffer[i]=queueBuffer.poll();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            switch (sHead){
                case 0xbe:
                    System.out.println( Integer.toHexString(packBuffer[1]));
                    json.put("rpm",(short)packBuffer[1]&0xff);
                    break;//发动机转速
                case 0x64:
                    json.put("pressure",(short)packBuffer[1]&0xff);
                    break;//机油压力
                case 0x6e:
                    if(packBuffer[2]==0xff){
                        json.put("temp",(short)packBuffer[1]&0xff-256);
                    }else{
                        json.put("temp",(short)packBuffer[1]&0xff-256);
                    }

                    break;//发动机水温
                case 0xb8:
                    json.put("fuelWear",(short)packBuffer[1]&0xff);
                    break;//当前油耗
                case 0x60:
                    json.put("oilMass",(short)packBuffer[1]&0xff);
                    break;//燃油箱油量
                case 0xfa:
                    json.put("fuelWears",(short)packBuffer[1]&0xff);
                    break;//总计油耗
                case 0xb7:
                    json.put("fuelRate",(short)packBuffer[1]&0xff);
                    break;//燃油消耗率
                case 0xf7:
                    json.put("EngineTime",(short)packBuffer[1]&0xff);
                    break;//发动机运行时间
                case 0x54:
                    json.put("s",(short)packBuffer[1]&0xff);
                    break;//车速
                case 0x95:
                    json.put("mileage",(short)packBuffer[1]&0xff);
                    break;//总计里程

            }
        }

        return json.toJSONString();
    }

    /**
     * 解析定位器指令
     * @param bytes
     * @return
     */
    public static String DateDecodeHande(byte[] bytes, ChannelHandlerContext ctx){
        ByteBuf msg= Unpooled.buffer();
        byte[] start={0x78,0x78};
        byte[] end={0x0d,0x0a};
        byte[] packBuffer =null;
        int sHead;
        JSONObject json=new JSONObject();
            sHead=bytes[3]& 0xFF;
            switch (sHead){
                case 0x01:ctx.channel().writeAndFlush(msg.writeBytes(bytes));break; //登录
                case 0x08:break; //心跳包
                case 0x10:ctx.channel().writeAndFlush(inita(sHead,getCMT0(1)));json.put("gps",decGPS(bytes));break;//GPS定位数据包
                case 0x13:Calendar cd = Calendar.getInstance();
                    System.out.println("电量："+(short)(bytes[4]&0xFF)+"时间："+new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss").format(cd.getTime()));break;//状态包
                case 0x14:break;//设备休眠命令
                case 0x15:break;//恢复出厂设置
                case 0x17:ctx.channel().writeAndFlush(inita(sHead,getCMT0(0)));json.put("gps",decWifLbs(bytes));break;//离线wifi数据
                case 0x30:ctx.channel().writeAndFlush(inita(sHead,getCMT0(1)));break;//更新时间
                case 0x33:break;//禁止LBS定位
                case 0x69:ctx.channel().writeAndFlush(inita(sHead,getCMT0(0)));json.put("gps",decWifLbs(bytes));break;//WIFI定位数据包
                case 0x81:break;//充电完成
                case 0x82:break;//充电连接
                case 0x83:break;//充电断开
                case 0x86:break;//超速报警
                case 0x94:break;//震动报警
                case 0x99:break;//sos报警
            }


        return json.toJSONString();
    }

    public static ByteBuf ServerHex(int head){
        switch (head){

        }
        return null;
    }

    public static   ByteBuf inita(int dex,byte[] data){
        int length=data.length+1;
        byte[] start={0x78,0x78, (byte) length, (byte) dex};

        byte[] end={0x0d,0x0a};
        ByteBuf msg= Unpooled.buffer();
        msg.writeBytes(start);
        msg.writeBytes(data);
        msg.writeBytes(end);
        return msg;
    }

    public static byte[] getCMT0(int i){
        TimeZone zone = TimeZone.getTimeZone("GMT-8:00");
        Calendar cd = Calendar.getInstance();

            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String hex = str2HexStr(df.format(cd.getTime()));
            if(i==0){
               return str2Bcd(str2HexStr(df.format(cd.getTime())));
            }
            return hex.getBytes();
    }
    /**
     * @功能: 10进制串转为BCD码
     * @参数: 10进制串
     * @结果: BCD码
     */
    public static byte[] str2Bcd(String asc) {
        int len = asc.length();
        int mod = len % 2;
        if (mod != 0) {
            asc = "0" + asc;
            len = asc.length();
        }
        byte abt[] = new byte[len];
        if (len >= 2) {
            len = len / 2;
        }
        byte bbt[] = new byte[len];
        abt = asc.getBytes();
        int j, k;
        for (int p = 0; p < asc.length() / 2; p++) {
            if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
                j = abt[2 * p] - '0';
            } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
                j = abt[2 * p] - 'a' + 0x0a;
            } else {
                j = abt[2 * p] - 'A' + 0x0a;
            }
            if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
                k = abt[2 * p + 1] - '0';
            } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
                k = abt[2 * p + 1] - 'a' + 0x0a;
            } else {
                k = abt[2 * p + 1] - 'A' + 0x0a;
            }
            int a = (j << 4) + k;
            byte b = (byte) a;
            bbt[p] = b;
        }
        return bbt;
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**16进制转为字符串
     * 16进制直接转换成为字符串(无需Unicode解码)
     * @param hexStr
     * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 处理基站定位数据
     * @param bytes
     * @return
     */
    public static String decWifLbs(byte[] bytes){
        //78 78 06 17 18 08 04 09 42 44 a8 15 4d fa 17 7a 5a 40 f4 20 c1 57 22 50 94 d9 b3 2d 51 b5 3e 48 7d 2e dd df e0 58 00 27 1d 04 b4 47 57 fc 7c 02 60 cf b7 58 02 01 cc 00 27 17 29 e8 5a 27 17 cb 96 64 0d 0a
        int wifiNum=(short)(bytes[2]&0xFF);
        System.out.println("wifi个数:"+wifiNum);
        int lbsNum=0;
        if(wifiNum>0){
            lbsNum=(short)(bytes[9+wifiNum*7+1]&0xFF);
        }
        System.out.println("基站个数:"+lbsNum);
        int max=9+wifiNum*7+1;
        int mciss=0;
        JSONObject obj=new JSONObject();
        for (int j = 0; j < lbsNum; j++) {
            if(mciss<Integer.parseInt(Integer.toHexString(bytes[max+8]&0xFF),16)){
                obj.put("mnc",(short)(bytes[max+3]&0xFF));
                obj.put("lac",Integer.parseInt(Integer.toHexString(bytes[max+4]&0xFF)+Integer.toHexString(bytes[max+5]&0xFF),16));
                obj.put("cell",Integer.parseInt(Integer.toHexString(bytes[max+6]&0xFF)+Integer.toHexString(bytes[max+7]&0xFF),16));
                obj.put("mciss",Integer.parseInt(Integer.toHexString(bytes[max+8]&0xFF),16));
                mciss=Integer.parseInt(Integer.toHexString(bytes[max+8]&0xFF),16);
            }
        }
        obj.put("ishex",10);
        obj.put("apikey","DA2272245C69F81E11BBB23371EA495C");
        obj.put("user_id",2294);

        if(mciss>0){
             obj= JSON.parseObject(HttpUtil.get("http://www.jizhanyun.com/api/",JSONObject.parseObject(obj.toJSONString(), new TypeReference<Map<String, Object>>(){})));
            System.out.println(obj.toJSONString());
             obj=GPSTOGAODe(obj.getJSONArray("data").getJSONObject(0).getString("lng")+","+obj.getJSONArray("data").getJSONObject(0).getString("lat"));
        }
        return obj.toJSONString();
    }

    public static JSONObject GPSTOGAODe(String logn){
        System.out.println(logn);
        Map<String,Object> map=new HashMap<>();
        map.put("key","bfc46b58e15af04041da2831f464d6a3");
        map.put("locations",logn);
        map.put("coordsys","gps");
        return JSON.parseObject(HttpUtil.get("https://restapi.amap.com/v3/assistant/coordinate/convert",map));
    }

    public static String decGPS(byte[] bytes){
        char[] hex=Integer.toHexString(bytes[10]).toCharArray();
        int gpsLength=(short)(hex[0]&0xFF);
        int gpsNum=(short)(hex[1]&0xFF);

        String lon="";
        for (int i = 11; i < 15; i++) {
            byte aByte = bytes[i];
            String k=Integer.toHexString(aByte&0xFF);
            if(k.length()<2){
                k="0"+k;
            }
            lon=lon+k;
        }
        String lat="";
        for (int i = 15; i < 19; i++) {
            byte aByte = bytes[i];
            String k=Integer.toHexString(aByte&0xFF);
            if(k.length()<2){
                k="0"+k;
            }
            lat=lat+k;
        }
        JSONObject jsonObject=GPSTOGAODe(WGS84(lat)+","+WGS84(lon));
        return jsonObject.toJSONString();
    }

    public static double WGS84(String lon){
        double l=Long.parseLong(lon,16)/30000d/60d;
        return l;
    }
}
